package cn.edu.ncu.housinghub.mapper;

import cn.edu.ncu.housinghub.entity.appointment.Appointment;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface AppointmentMapper {

    /**
     * 插入预约信息
     * @param appointment 预约信息
     */
    @Insert("INSERT INTO appointment (tenantId, houseId, landlordId, agentId, appointmentTime, isRefused, refusedReason) " +
            "VALUES (#{tenantId}, #{houseId}, #{landlordId}, #{agentId}, #{appointmentTime}, #{isRefused}, #{refusedReason})")
    @Options(useGeneratedKeys = true, keyProperty = "appointmentId")
    void insertAppointment(Appointment appointment);

    /**
     * 根据中介ID获取所有预约申请
     */
    @Select("SELECT a.appointmentId, a.tenantId, a.houseId, a.landlordId, a.agentId, " +
            "a.appointmentTime, a.isRefused, a.refusedReason, a.remarkMessage, " +
            "u.username as tenantName, u.phone as tenantPhone, " +
            "h.houseTitle, h.houseSummary, h.houseLocation " +
            "FROM appointment a " +
            "LEFT JOIN user u ON a.tenantId = u.userId " +
            "LEFT JOIN house h ON a.houseId = h.houseId " +
            "WHERE a.agentId = #{agentId} " +
            "ORDER BY a.appointmentTime DESC")
    List<Appointment> selectAppointmentsByAgentId(Long agentId);

    /**
     * 根据中介ID获取待处理的预约申请
     */
    @Select("SELECT a.appointmentId, a.tenantId, a.houseId, a.landlordId, a.agentId, " +
            "a.appointmentTime, a.isRefused, a.refusedReason, a.remarkMessage, " +
            "u.username as tenantName, u.phone as tenantPhone, " +
            "h.houseTitle, h.houseSummary, h.houseLocation " +
            "FROM appointment a " +
            "LEFT JOIN user u ON a.tenantId = u.userId " +
            "LEFT JOIN house h ON a.houseId = h.houseId " +
            "WHERE a.agentId = #{agentId} AND a.isRefused IS NULL " +
            "ORDER BY a.appointmentTime ASC")
    List<Appointment> selectPendingAppointmentsByAgentId(Long agentId);

    /**
     * 根据房源ID获取预约申请
     */
    @Select("SELECT a.appointmentId, a.tenantId, a.houseId, a.landlordId, a.agentId, " +
            "a.appointmentTime, a.isRefused, a.refusedReason, a.remarkMessage, " +
            "u.username as tenantName, u.phone as tenantPhone, " +
            "h.houseTitle, h.houseSummary, h.houseLocation " +
            "FROM appointment a " +
            "LEFT JOIN user u ON a.tenantId = u.userId " +
            "LEFT JOIN house h ON a.houseId = h.houseId " +
            "WHERE a.houseId = #{houseId} " +
            "ORDER BY a.appointmentTime DESC")
    List<Appointment> selectAppointmentsByHouseId(Long houseId);

    /**
     * 更新预约状态（同意或拒绝）
     */
    @Update("UPDATE appointment SET isRefused = #{isRefused}, refusedReason = #{refusedReason} " +
            "WHERE appointmentId = #{appointmentId}")
    void updateAppointmentStatus(@Param("appointmentId") Long appointmentId,
                               @Param("isRefused") Boolean isRefused,
                               @Param("refusedReason") String refusedReason);

    /**
     * 根据预约ID获取预约详情
     */
    @Select("SELECT a.appointmentId, a.tenantId, a.houseId, a.landlordId, a.agentId, " +
            "a.appointmentTime, a.isRefused, a.refusedReason, a.remarkMessage, " +
            "u.username as tenantName, u.phone as tenantPhone, " +
            "h.houseTitle, h.houseSummary, h.houseLocation " +
            "FROM appointment a " +
            "LEFT JOIN user u ON a.tenantId = u.userId " +
            "LEFT JOIN house h ON a.houseId = h.houseId " +
            "WHERE a.appointmentId = #{appointmentId}")
    Appointment selectAppointmentById(Long appointmentId);

    /**
     * 根据中介用户ID和状态获取预约列表
     * 状态：0=待处理，1=已确认，-1=已拒绝，2=已完成
     */
    @Select("SELECT a.appointmentId, a.tenantId, a.houseId, a.landlordId, a.agentId, " +
            "a.appointmentTime, a.isRefused, a.refusedReason, a.remarkMessage, " +
            "u.username as tenantName, u.phone as tenantPhone, " +
            "h.houseTitle, h.houseSummary, h.houseLocation " +
            "FROM appointment a " +
            "LEFT JOIN user u ON a.tenantId = u.userId " +
            "LEFT JOIN house h ON a.houseId = h.houseId " +
            "LEFT JOIN agent ag ON a.agentId = ag.agentId " +
            "WHERE ag.userId = #{agentUserId} " +
            "AND CASE " +
            "  WHEN #{status} = 0 THEN a.isRefused IS NULL " +
            "  WHEN #{status} = 1 THEN a.isRefused = false " +
            "  WHEN #{status} = -1 THEN a.isRefused = true " +
            "  WHEN #{status} = 2 THEN a.isRefused = false AND a.appointmentTime < NOW() " +
            "END " +
            "ORDER BY a.appointmentTime DESC")
    List<Appointment> selectAgentAppointmentsByStatus(@Param("agentUserId") Long agentUserId,
                                                     @Param("status") Integer status);

    /**
     * 根据中介用户ID获取所有预约
     */
    @Select("SELECT a.appointmentId, a.tenantId, a.houseId, a.landlordId, a.agentId, " +
            "a.appointmentTime, a.isRefused, a.refusedReason, a.remarkMessage, " +
            "u.username as tenantName, u.phone as tenantPhone, " +
            "h.houseTitle, h.houseSummary, h.houseLocation " +
            "FROM appointment a " +
            "LEFT JOIN user u ON a.tenantId = u.userId " +
            "LEFT JOIN house h ON a.houseId = h.houseId " +
            "LEFT JOIN agent ag ON a.agentId = ag.agentId " +
            "WHERE ag.userId = #{agentUserId} " +
            "ORDER BY a.appointmentTime DESC")
    List<Appointment> selectAllAgentAppointments(Long agentUserId);

    /**
     * 更新预约状态（使用整数状态）
     * 状态：0=待处理，1=已确认，-1=已拒绝，2=已完成
     */
    @Update("UPDATE appointment SET " +
            "isRefused = CASE " +
            "  WHEN #{status} = 1 THEN false " +
            "  WHEN #{status} = -1 THEN true " +
            "  ELSE isRefused " +
            "END, " +
            "refusedReason = #{reason} " +
            "WHERE appointmentId = #{appointmentId}")
    void updateAppointmentStatusByCode(@Param("appointmentId") Long appointmentId,
                                      @Param("status") Integer status,
                                      @Param("reason") String reason);
}